class MyBlockingQueue{
    private String[] elems=null;
    private int head=0;
    private int tail=0;
    private int size=0;

    private static Object locker=new Object();

    public MyBlockingQueue(int capacity){
        elems=new String[capacity];
    }

    public void put(String elem) throws InterruptedException {

        synchronized (locker) {
            while(size >= elems.length) {
                //队列满了，此处要能够阻塞
                locker.wait();
            }

            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (locker) {
            String elem = null;
            while(size == 0) {
                locker.wait();
            }
            elem = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            locker.notify();
            return elem;
        }
    }

}

public class ThreadDemo4 {
    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue(5);
        //生产者
        Thread t1=new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            int n=1;
           while(true){
               try {
                   queue.put(n+"");
                   System.out.println("生产元素 "+n);
                   n++;
                   //Thread.sleep(500);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        //消费者
        Thread t2=new Thread(()->{
            while(true){
                try {
                    String n=queue.take();
                    System.out.println("消费元素 "+n);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();

    }
}

